package org.ttitfly.workflow.engine;

import java.util.Date;
import java.util.List;

import org.ttitfly.workflow.Session;
import org.ttitfly.workflow.SessionHolder;
import org.ttitfly.workflow.engine.run.ProcessInstance;
import org.ttitfly.workflow.engine.run.Task;
import org.ttitfly.workflow.handler.Handler;


/**
 * 任务类运行单元基类，封装了父流程
 * 
 * @author 潘海春
 * @version 2009-9-11
 */
public abstract class TaskRunUnit extends AbstractRunUnit {
	
	/**
	 * 默认描述任务的KEY
	 */
	public static final String TASK_DESCRIPTION_KEY = "description";
	
	/**
	 * 默认任务处理备注的KEY
	 */
	public static final String TASK_REMARK_KEY = "remark";

	/**
	 * 流程
	 */
	protected Process parent;

	/**
	 * 构造函数
	 * 
	 * @param parent
	 * @param name
	 */
	public TaskRunUnit(Process parent, String name) {
		this(parent, name, null, null);
	}

	/**
	 * 构造函数
	 * 
	 * @param parent
	 * @param name
	 * @param activeHandlers
	 * @param closeHandlers
	 */
	public TaskRunUnit(Process parent, String name,
			List<Handler> activeHandlers, List<Handler> closeHandlers) {
		super(name, activeHandlers, closeHandlers);
		this.parent = parent;
	}

	@Override
	protected void onInit() throws Exception {
		SessionHolder.currentSession().setCurrent(openTask());
	}

	/**
	 * 初始化任务数据
	 * 
	 * @return
	 */
	protected Task openTask() {
		Task task = new Task();
		Session session = SessionHolder.currentSession();
		ProcessInstance pi = session.currentProcessInstance();
		task.setProcessInstance(pi);
		task.setDescription((String) session.getVariable(TASK_DESCRIPTION_KEY));
		pi.getTasks().add(task);
		task.setUnitName(getName());
		task.setPrevious(session.currentTask());
		return task;
	}

	@Override
	protected void onActive() throws Exception {
		SessionHolder.currentSession().currentTask().setActivationTime(new Date());
	}

	@Override
	protected void onClose() throws Exception {
		Task task = SessionHolder.currentSession().currentTask();
		task.setOperator(SessionHolder.currentSession().getPrincipal());
		task.setCloseTime(new Date());
	}

	@Override
	protected int getStatus() {
		return SessionHolder.currentSession().currentTask().getStatus();
	}

	@Override
	protected void setStatus(int status) {
		SessionHolder.currentSession().currentTask().setStatus(status);
	}

}
